import 'package:flutter/material.dart';
import '../core/gitcode_api.dart';

/// 自定义用户列表卡片组件
/// 封装了用户信息的展示，包括头像、名称、登录名、注册时间等
class UserCard extends StatelessWidget {
  const UserCard({
    super.key,
    required this.user,
    this.onTap,
    this.height,
  });

  final GitCodeSearchUser user;
  final VoidCallback? onTap;
  /// 卡片固定高度，默认为 120
  final double? height;

  // 固定每行的高度常量
  static const double _avatarSize = 40.0;          // 头像大小
  static const double _titleRowHeight = 20.0;      // 用户名称行高度
  static const double _loginRowHeight = 18.0;      // 登录名行高度
  static const double _infoRowHeight = 18.0;       // 信息行高度（注册时间）
  static const double _urlRowHeight = 18.0;        // 地址行高度
  static const double _spacing = 6.0;               // 行间距
  static const double _padding = 12.0;              // 内边距

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final muted = theme.colorScheme.onSurfaceVariant;
    final linkColor = theme.colorScheme.primary;
    // 计算实际需要的高度：padding(上下) + 头像区域 + 间距 + 名称 + 间距 + 登录名 + 间距 + 注册时间 + 间距 + 地址
    // 增加8px余量以防止溢出
    final calculatedHeight = _padding * 2 +
        _avatarSize +
        _spacing +
        _titleRowHeight +
        _spacing +
        _loginRowHeight +
        _spacing +
        _infoRowHeight +
        _spacing +
        _urlRowHeight +
        8.0; // 额外余量防止溢出
    final cardHeight = height ?? calculatedHeight;

    final displayName = user.name?.isNotEmpty == true ? user.name! : user.login;

    return SizedBox(
      height: cardHeight,
      child: Card(
        elevation: 2,
        margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
        child: InkWell(
          onTap: onTap,
          borderRadius: BorderRadius.circular(12),
          child: Padding(
            padding: const EdgeInsets.all(_padding),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 左侧：头像
                CircleAvatar(
                  radius: _avatarSize / 2,
                  backgroundImage: NetworkImage(user.avatarUrl),
                  onBackgroundImageError: (_, __) {},
                  backgroundColor: theme.colorScheme.surfaceContainerHighest,
                  child: user.avatarUrl.isEmpty
                      ? Icon(
                          Icons.person,
                          size: _avatarSize / 2,
                          color: theme.colorScheme.onSurfaceVariant,
                        )
                      : null,
                ),
                const SizedBox(width: 12),
                // 右侧：用户信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      // 第1行：用户名称（固定高度）
                      SizedBox(
                        height: _titleRowHeight,
                        child: Text(
                          displayName,
                          style: theme.textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.bold,
                            fontSize: 16,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      const SizedBox(height: _spacing),
                      // 第2行：登录名（固定高度，移除@符号）
                      SizedBox(
                        height: _loginRowHeight,
                        child: Row(
                          children: [
                            Icon(
                              Icons.person_outline,
                              size: 14,
                              color: muted,
                            ),
                            const SizedBox(width: 4),
                            Expanded(
                              child: Text(
                                user.login,
                                style: theme.textTheme.bodyMedium?.copyWith(
                                  color: muted,
                                  fontSize: 13,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: _spacing),
                      // 第3行：注册时间（固定高度）
                      SizedBox(
                        height: _infoRowHeight,
                        child: user.createdAt != null
                            ? Row(
                                children: [
                                  Icon(
                                    Icons.calendar_today,
                                    size: 13,
                                    color: muted,
                                  ),
                                  const SizedBox(width: 4),
                                  Expanded(
                                    child: Text(
                                      '注册于 ${_formatDate(user.createdAt!)}',
                                      style: theme.textTheme.bodySmall?.copyWith(
                                        color: muted,
                                        fontSize: 12,
                                      ),
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                ],
                              )
                            : const SizedBox.shrink(),
                      ),
                      const SizedBox(height: _spacing),
                      // 第4行：地址（固定高度）
                      SizedBox(
                        height: _urlRowHeight,
                        child: user.htmlUrl != null && user.htmlUrl!.isNotEmpty
                            ? Row(
                                children: [
                                  Icon(
                                    Icons.link,
                                    size: 13,
                                    color: muted,
                                  ),
                                  const SizedBox(width: 4),
                                  Expanded(
                                    child: Text(
                                      user.htmlUrl!,
                                      style: theme.textTheme.bodySmall?.copyWith(
                                        color: linkColor,
                                        fontSize: 12,
                                      ),
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                ],
                              )
                            : const SizedBox.shrink(),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 格式化日期，简化显示
  String _formatDate(String dateString) {
    try {
      // 尝试解析 ISO 8601 格式的日期
      final date = DateTime.parse(dateString);
      // 格式化为 YYYY-MM-DD
      return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
    } catch (e) {
      // 如果解析失败，返回原始字符串（截取前10个字符）
      return dateString.length > 10 ? dateString.substring(0, 10) : dateString;
    }
  }
}

